package cn.atguigu.stack;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 逆波兰计算器
 */
public class PolandNotation {

    public static void main(String[] args) {
        String suffixExpression = "3 4 + 5 * 6 -";
        PolandNotation polandNotation = new PolandNotation();
        List<String> list = polandNotation.stringToArray(suffixExpression);
        System.out.println(list);
        int calculate = polandNotation.calculate(list);
        System.out.println("计算结果："+calculate);


    }

    public List<String> stringToArray(String s){
        return Arrays.asList(s.split(" "));
    }

    public int calculate(List<String> ls){
        Stack<String> stack = new Stack<>();
        for (String item :ls) {
            if(item.matches("\\d+")){
                stack.push(item);
            }else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;
                switch (item) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num2 - num1;
                        break;
                    case "*":
                        res = num2 * num1;
                        break;
                    case "/":
                        res = num2 / num1;
                        break;
                    default:
                        throw new RuntimeException("运算符不正确");

                }
                stack.push(String.valueOf(res));
            }
        }

        return Integer.parseInt(stack.pop());
    }
}
